<template>
  <el-dialog
    style="border-radius: 0 !important; padding: 0 !important"
    v-model="open"
    :fullscreen="true"
    :show-close="false"
    class="contract-dialog"
    custom-class="contract-dialog"
    @close="close"
  >
    <!-- Dialog Header -->
    <template #header>
      <div class="dialog-header">
        <div class="header-left">
          <el-icon class="back-btn" @click="close"><Back size="28px" /></el-icon>

          <span class="title">{{ title }}</span>
        </div>
        <div class="header-right">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </div>
    </template>

    <!-- Dialog Content -->
    <div class="dialog-content">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="contract-form" label-position="top">
        <!-- Basic Information -->
        <div class="form-section">
          <div class="section-title">
            <div class="title-marker"></div>
            基本信息
          </div>
          <div>
            <div class="form-grid">
              <el-form-item label="任务类型" prop="taskTypeId">
                <el-select v-model="form.taskTypeId" placeholder="请选择" @change="(val) => getFollowStatus(val)" clearable>
                  <el-option v-for="(item, index) in taskTypes" :key="index" :label="item.taskTypeName" :value="item.id"></el-option>
                  <template #footer>
                    <div>
                      <el-button
                        style="width: 120px; margin: 0 auto"
                        plain
                        color="#626aef"
                        :dark="false"
                        size="small"
                        @click="addClueSource"
                        :icon="Plus"
                      >
                        <el-icon color="fff"><Plus /></el-icon>添加
                      </el-button>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item label="客户分类" prop="supplierClassifyId">
                <el-tree-select
                  node-key="id"
                  v-model="form.supplierClassifyId"
                  :data="classifyList"
                  :render-after-expand="false"
                  default-expand-all
                />
              </el-form-item>
              <el-form-item label="日期" prop="programDate ">
                <el-date-picker
                  v-model="form.programDate"
                  type="date"
                  value-format="YYYY-MM-DD hh:mm:ss"
                  placeholder="请选择"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="客户经理" prop="userId">
                <el-select v-model="form.userId" clearable reserve-keyword placeholder="请选择客户经理">
                  <el-option v-for="item in userList" :key="item.userId" :label="item.realityName" :value="item.userId" />
                </el-select>
              </el-form-item>
              <el-form-item label="经营类型" prop="followTypeId">
                <el-select v-model="form.followTypeId" placeholder="请选择" @change="(val) => getFollowStatus(val)" clearable>
                  <el-option v-for="(item, index) in followTypes" :key="index" :label="item.typeName" :value="item.id"></el-option>                  
                  <template #footer>
                    <div>
                      <el-button
                        style="width: 120px; margin: 0 auto"
                        plain
                        color="#626aef"
                        :dark="false"
                        size="small"
                        @click="addFormType"
                        :icon="Plus"
                      >
                        <el-icon color="fff"><Plus /></el-icon>添加
                      </el-button>
                    </div>
                  </template>
                </el-select>
              </el-form-item>

              <el-form-item label="备注">
                <el-input v-model="form.remark" placeholder="请输入"></el-input>
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- Sales Information -->
        <div class="form-section">
          <div class="products-table">
            <div class="table-header">
              <div style="display: flex; align-items: center">
                <div class="title-marker"></div>
                <span>关联客户</span>
              </div>
              <div class="table-actions">
                <el-button type="primary" @click="showCustomer" :disabled="!form.userId || !form.supplierClassifyId"
                  ><el-icon><Plus color="#fff" /></el-icon>批量添加</el-button
                >
              </div>
            </div>
            <el-table
              header-align="center"
              :data="dataSource"
              border
              style="width: 100%"
              :span-method="objectSpanMethod"
              :header-cell-style="getHeaderStyle"
              scrollbar-always-on
            >
              <!-- Basic Information Columns -->
              <el-table-column type="index" label="序号" width="70"></el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button type="text" @click="handleCopy(scope.$index)">
                    <el-icon><CopyDocument /></el-icon>
                  </el-button>
                  <el-button type="text" @click="handleDelete(scope.$index)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="supplierName" label="客户名称" min-width="120"></el-table-column>
              <el-table-column prop="supplierClassifyName" label="客户分类" width="100"></el-table-column>
              <el-table-column prop="userName" label="客户经理" width="100"></el-table-column>
              <el-table-column prop="missingDays" label="未联系天数" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.missingDays" placeholder="" size="normal" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="lastVisitDate" label="上次拜访时间" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.lastVisitDate" placeholder="" size="normal" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="lastVisitTime" label="合同名称" width="150">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.contractName"
                    placeholder="请选择合同"
                    size="normal"
                    clearable
                    @click="handleAddContract(scope.$index)"
                    @clear="clearContract(scope.$index)"
                  >
                    <template #suffix>
                      <el-icon class="el-input__icon"><search /></el-icon>
                    </template>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column prop="beginDate" label="合同开始日期" width="150">
                <template #default="scope">
                {{ scope.row.contractId &&  scope.row.beginDate ? moment(scope.row.beginDate).format('YYYY-MM-DD') : '' }}
                </template>

              </el-table-column>
              <el-table-column prop="endDate" label="合同结束日期" width="150">
                <template #default="scope">
                {{ scope.row.contractId &&  scope.row.endDate ? moment(scope.row.endDate).format('YYYY-MM-DD') : '' }}
                </template>
              </el-table-column>
              <el-table-column prop="remainingDays" label="剩余天数" width="150">
                <template #default="scope">
                  <el-input :disabled="scope.row.contractId" @change="daysChange(scope.$index)" v-model="scope.row.remainingDays" placeholder="" size="normal" clearable></el-input>
                </template>
              </el-table-column>

              <template v-for="(item, index) in followStatus" :key="index">
                <el-table-column :prop="getPropStr(index)" :label="item.name" min-width="180">
                  
                  <template #default="scope">
                  {{ scope.row[getPropStr(index)] ? moment(scope.row[getPropStr(index)]).format('YYYY-MM-DD') : '' }}
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </div>
        </div>
      </el-form>
      <custom-dialog :query="cusQuery" ref="customDialog" @ok="customerOk"></custom-dialog>
      <select-material-form ref="selectMaterialForm" @ok="selectOk"></select-material-form>
      <select-clue-form ref="selectClueForm" @ok="clueOk"></select-clue-form>
      <clueSourceAddForm ref="clueSourceAddForm" @ok="listTaskType"></clueSourceAddForm>
      <contractDialog ref="contractDialog" @ok="contractOk"></contractDialog>
  <AddFormType ref="addFormType" @ok="addTypeOk"></AddFormType>
    </div>
  </el-dialog>
</template>
  
  <script>
import customDialog from './custom-dialog.vue';
import contractDialog from '@/views/goods/crmContract/modules/contract-dialog.vue';
import modelMixin from '@/mixins/modelMixin';
import selectMaterialForm from '@/views/goods/quote/modules/selectMaterialForm';
import selectClueForm from '@/views/goods/clue/modules/clue-dialog.vue';
import clueSourceAddForm from '@/views/goods/clueSource/modules/addForm.vue';
import AddFormType from '@/views/goods/followType/modules/addForm';
import { formatDate } from '@/utils/index';
import { globalHeaders } from '@/utils/request';
import visitorProgram from '@/api/goods/visitorProgram';
import { getSupplier } from '@/api/goods/supplier/index';
import { listByTypeId } from '@/api/goods/followStage';
import { listTaskType } from '@/api/goods/taskType';
import moment from 'moment';
export default {
  name: 'VisitorPlanDialog',
  components: {
    customDialog,
    selectMaterialForm,
    selectClueForm,
    clueSourceAddForm,
    contractDialog,
    AddFormType,
  },
  mixins: [modelMixin],
  data() {
    return {
      open: false,
      funcObj: visitorProgram,
      uploadUrl: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload', // 上传的图片服务器地址
      title: '',
      headers: globalHeaders(),
      fileList: [],
      dataSource: [],
      fileUrls: [],
      followStatus: [],
      form: {},
      currentTableIndex: -1,
      taskTypes: [],
      dataSource: [],
      rules: {
        taskTypeId: [{ required: true, message: '请选择任务类型', trigger: 'blur' }],
        supplierClassifyId: [{ required: true, message: '请选择客户分类', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择客户经理', trigger: 'blur' }],
        followTypeId: [{ required: true, message: '请选择经营类型', trigger: 'change' }]
      }
    };
  },
  created() {
    // 销售区域
    this.getArea();
    this.getUserNotPermission();
    // 经营类型
    this.listFollowType(0);
    // 所有后台用户
    this.getUserAllList();
    // 客户分类
    this.getClassifyTree(1);
    // 任务类型
    this.listTaskType();
  },
  computed: {
    cusQuery() {
      console.log('666', 666);
      return {
        supplierClassifyId: this.form.supplierClassifyId,
        operationManager: this.form.userId
      };
    },
    ctQuery() {
      return {
        supplierId: this.currentTableIndex > -1 && this.dataSource.length? this.dataSource[this.currentTableIndex].supplierId : undefined
      };
    },
  },
  watch: {
    userList(newValue, oldValue) {
      const user = this.userList.find((v) => v.userId === this.form.userId);
      this.dataSource = newValue.map((v) => {
        v.userName = user.realityName;
        return v;
      });
    }
  },
  methods: {
    add() {
      this.open = true;
      this.title = '新增访客计划';
      this.$nextTick(() => {
        this.form.programDate = moment().format('YYYY-MM-DD hh:mm:ss');
        this.$refs.form.clearValidate();
      });
    },
    edit(row) {
      this.title = '编辑访客计划';
      this.open = true;
      this.getDetail(row);
    },
    getPropStr(index) {
      return `dateFreeItem` + ((index + 1) < 10 ? '0' + (index + 1) : (index + 1));
    },
    detailAfter() {
      
      const user = this.userList.find((v) => v.userId === this.form.userId);
      this.dataSource = this.form.jzgVisitorProgramDetailVoList.map((v) => {
              v.userName = user.realityName;
              return v;

      });
      
      this.getFollowStatus(this.form.followTypeId)
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    
    addTypeOk() {
    this.listFollowType(0);
    },
    listTaskType() {
      listTaskType().then((res) => {
        this.taskTypes = res.rows;
      });
    },
    close() {
      this.open = false;
      this.form = {};
      this.dataSource = [];
      this.fileList = [];
      this.currentTableIndex = -1
    },
    handleAdd() {
      this.$refs.selectMaterialForm.show();
    },
    handleAddContract(index) {
      this.currentTableIndex = index;
      this.$refs.contractDialog.open(this.ctQuery);
    },
    // 删除关联产品
    handleDelete(index) {
      this.$modal.confirm('你确定要删除该条数据吗?').then(() => {
        this.dataSource.splice(index, 1);
      });
    },
    handleCopy(index) {
      this.dataSource.push(JSON.parse(JSON.stringify(this.dataSource[index])));
    },
    quantityChange(value, row, index) {
      if (row.goodsPrice && row.goodsNumber) {
        row.goodsAmount = row.goodsPrice * row.goodsNumber;
        this.dataSource.splice(index, 1, row);
      }
    },
    selectOk(data) {
      this.dataSource = data.map((v) => {
        let data = {
          ...v,
          goodsId: v.id,
          goodsPrice: v.retailPrice,
          goodsAmount: v.goodsAmount,
          comment: v.remark,
          goodsNumber: v.goodsNumber,
          goodsPriceTypeDictValue: v.goodsPriceTypeDictValue,
          brandName: v.brandName,
          goodsPackImg: v.packImg
        };
        delete data.id;
        return data;
      });
    },
    showCustomer() {
      this.$refs.customDialog.open();
    },
    handleAdd() {
      this.$refs.contractDialog.open();
    },
    showClue() {
      this.$refs.selectClueForm.open();
    },
    clueOk(rows) {
      let clue = rows[0];

      this.form.clueNumber = clue.clueName;
      this.form.clueId = clue.id;
    },
    customerOk(rows) {
      rows.forEach(customer=>{
        const user = this.userList.find((v) => v.userId === this.form.userId);
        console.log(user, 'user');
        this.dataSource.push({
          supplierId: customer.id,
          supplierName: customer.supplierName,
          supplierClassifyId: customer.supplierClassifyId,
          supplierClassifyName: customer.supplierClassifyName,
          userName: (user && user.realityName) || '-'
        });
      })
    },

    handlePeriodicNumChange(row) {
      if (row.beginDate && row.periodicNum > 0) {
        let date = row.beginDate;
        date = Date.parse(new Date(date)) / 1000; // 转换成时间戳，返回值是ms，除1000后转化成秒
        date += 86400 * row.periodicNum; // 一天是86400秒
        let newDate = new Date(parseInt(date) * 1000); // 把时间戳转换成日期
        //这步就是给所需变化的值赋值
        row.endDate = formatDate(newDate);
      }
    },
    handleEndDateChange(row) {
      if (row.beginDate && row.endDate) {
        let date1 = Date.parse(new Date(row.beginDate));
        let date2 = Date.parse(new Date(row.endDate));
        row.periodicNum = parseInt(Math.abs(date2 - date1) / 1000 / 86400);
      }
    },

    addClueSource() {
      this.$refs.clueSourceAddForm.add({}, 5);
    },
    addFormType() {
      this.$refs.addFormType.add({typeCategory:0});
    },
    // 上传成功
    handleUploadSuccess(res, file, key) {
      // 如果上传成功
      if (res.code == 200) {
        this.fileUrls.push(res.data.url);
      } else {
        this.$modal.msgError(res.msg);
      }
      console.log(this.fileList, '123');
    },

    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('submit', this.form);
          this.close();
        }
      });
    },

    // 根据任务类型获取任务阶段
    getFollowStatus(id) {
      if (!id) {
        this.followStatus = [];
        return;
      }

      listByTypeId(id).then((res) => {
        this.followStatus = res || [];
      });
    },
    validateForm() {
      if (!this.dataSource.length) {
        this.$modal.msgError('请选择关联客户！');
        return false;
      }
      for (let i = 0; i < this.dataSource.length; i++) {
        for (let j = 0; j < this.followStatus.length; j++) {
          if (!this.dataSource[i][`dateFreeItem${(j + 1) < 10 ? '0' + (j + 1) : (j + 1)}`]) {
            this.$modal.msgError(`请填写第${i + 1}行第${j + 1}个阶段的排期！`);
            return false;
          }
        }
      }
      return true;
    },
    // 组装待提交的数据
    classifyForm() {
      if (!this.validateForm()) {
        throw new Error('表单验证失败');
      }
      this.form.jzgVisitorProgramDetailVoList = this.dataSource;
    },
    contractOk(rows) {
      console.log('rows',rows);
      if (rows.length == 1) {
        const date1 = moment();
        const date2 = moment(rows[0].endDate);

        // 计算两个日期之间的天数差
        const daysDifference = date2.diff(date1, 'days');
        let contract = {
          contractId: rows[0].id,

          contractName: rows[0].contractName,
          beginDate: moment(rows[0].beginDate).format('YYYY-MM-DD HH:mm:ss'),
          endDate: moment(rows[0].endDate).format('YYYY-MM-DD HH:mm:ss'),
          remainingDays: daysDifference
        };
        let item = this.dataSource[this.currentTableIndex];
        item = Object.assign(item, contract);
        item = this.calculateSchedule(item);
        console.log(item, 'item');
        this.dataSource.splice(this.currentTableIndex, 1, item);
        console.log(this.dataSource, 'this.dataSource');
      } else {
        this.$modal.msgError('请选择一条合同信息！');
      }
    },
    clearContract(index){
      let item = this.dataSource[index];
      item.contractId = null;
      item.contractName = null;
      item.beginDate = null;
      item.endDate = null;
      item.remainingDays = '';
      for(let i = 0; i < this.followStatus.length; i++){
        item[`dateFreeItem${(i + 1) < 10 ? '0' + (i + 1) : (i + 1)}`] = '';
      }

    },
    daysChange(index){
      let item = this.dataSource[index];
      item = this.calculateSchedule(item);
      this.dataSource.splice(index, 1, item);
    },
    /**
     * 根据阶段周期计算排期
     * 公式：剩余天数 - （365 - 阶段周期） - 30 + 当前日期
     * */
    calculateSchedule(row) {
      for(let i = 0; i < this.followStatus.length; i++){
        if(row.remainingDays && row.remainingDays > 0){
          let result = moment().add(row.remainingDays - (365 - this.followStatus[i].stageCycle) - 30, 'days');
          console.log(result, 'result');
          row[`dateFreeItem${(i + 1) < 10 ? '0' + (i + 1) : (i + 1)}`] = result.format('YYYY-MM-DD HH:mm:ss');
        }
      }
      return row;
    }
  }
};
</script>
  
  <style scoped lang="scss">
.contract-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
}

.contract-dialog .el-dialog__header {
  display: none;
}

.contract-dialog .el-dialog__body {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 32px;
}
.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}
.header-left .el-button {
  font-size: 16px;
  font-weight: 500;
}

.header-right {
  display: flex;
  gap: 12px;
}

.dialog-content {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  overflow-y: hidden;
}
.contract-form {
  width: calc(100% - 48px);
  margin: 0 auto;
}
.back-btn {
  font-size: 28px;
}
.back-btn:hover {
  color: #2468f2;
  cursor: pointer;
}
.form-section {
  background: #fff;
  border-radius: 4px;
  padding: 24px;
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 24px;
}
.title {
  font-size: 14px;
}

.title-marker {
  width: 2px;
  height: 14px;
  background: #2468f2;
  margin-right: 8px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
}

.products-table {
  margin-top: 16px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.empty-products {
  padding: 32px;
  text-align: center;
  color: #909399;
}

.empty-icon {
  width: 64px;
  height: 64px;
  margin-bottom: 8px;
}

/* Element UI Overrides */
.el-form-item__label {
  font-weight: normal;
  color: #606266;
}

.el-input__inner,
.el-select .el-input__inner {
  height: 32px;
  line-height: 32px;
}

.el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label:before,
.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  color: #2468f2;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 500;
}

.el-button--primary {
  background-color: #2468f2;
  border-color: #2468f2;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #1d54cc;
  border-color: #1d54cc;
}
</style>
<style lang="scss">
.el-overlay .el-overlay-dialog .contract-dialog .el-dialog__body {
  padding: 0 !important;
}
.contract-dialog .el-dialog__body {
  min-height: calc(100vh - 57px) !important;
  background-color: #f5f7fa;
}
</style>